import cv2
from cv2 import ADAPTIVE_THRESH_GAUSSIAN_C
import numpy as np

img1 = cv2.imread('E:\\113.jpg')
img2 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY) #将图像转为灰度图

# 全局二值化
# ret, dst = cv2.threshold(img2, 125, 255, cv2.THRESH_BINARY)

# 自适应二值化
dst  = cv2.adaptiveThreshold(img2, 255, ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,3,0)

# 腐蚀
# kernel = np.ones((3,3), np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
dst = cv2.dilate(img1, kernel, iterations=1)

# 开运算
dst = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel)

# 梯度运算
dst = cv2.cv2.morphologyEx(img1, cv2.MORPH_GRADIENT, kernel)

# 顶帽运算
dst = cv2.morphologyEx(img1, cv2.MORPH_TOPHAT, kernel)

cv2.imshow('img1',img1)
cv2.imshow('img2',img2)
cv2.imshow('dst',dst)

cv2.waitKey(0)